package com.ydche.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisClient {

    @Autowired
    private JedisPool jedisPool;

    @Value("${redisKeyPrefix}")
    private String keyPrefix;

    public void set(String key, String value) throws Exception {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(keyPrefix + key, value);

        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    public void set(String key, String value, int expired) throws Exception {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.setex(keyPrefix+key, expired, value);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    public String get(String key) throws Exception {
        System.out.println("key prefix="+keyPrefix);
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(keyPrefix + key);
        } finally {
            jedis.close();
        }
    }

}
